package com.hltc.mtmap.orm;

import java.util.List;
import java.util.ArrayList;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

import com.hltc.mtmap.MTCategory;
import com.hltc.mtmap.MTSite;
import com.hltc.mtmap.MTUser;

import com.hltc.mtmap.MTGrain;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.

/**
 * DAO for table MTGRAIN.
 */
public class MTGrainDao extends AbstractDao<MTGrain, Long> {

    public static final String TABLENAME = "MTGRAIN";
    private DaoSession daoSession;
    ;
    private Query<MTGrain> mTUser_Grains2UserQuery;
    private Query<MTGrain> mTSite_Grains2SiteQuery;
    private Query<MTGrain> mTCategory_Grains2CategoryQuery;
    private String selectDeep;

    public MTGrainDao(DaoConfig config) {
        super(config);
    }

    public MTGrainDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /**
     * Creates the underlying database table.
     */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists ? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "'MTGRAIN' (" + //
                "'GRAIN_ID' INTEGER PRIMARY KEY NOT NULL ," + // 0: grainId
                "'TEXT' TEXT," + // 1: text
                "'CATE_ID' TEXT," + // 2: cateId
                "'CREATE_TIME' TEXT," + // 3: createTime
                "'IS_PUBLIC' INTEGER," + // 4: isPublic
                "'SITE_ID' TEXT NOT NULL ," + // 5: siteId
                "'CATEGORY_ID' INTEGER NOT NULL ," + // 6: categoryId
                "'USER_ID' INTEGER NOT NULL );"); // 7: userId
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'MTGRAIN'";
        db.execSQL(sql);
    }

    /** @inheritdoc */
    @Override
    protected void bindValues(SQLiteStatement stmt, MTGrain entity) {
        stmt.clearBindings();
        stmt.bindLong(1, entity.getGrainId());
 
        String text = entity.getText();
        if (text != null) {
            stmt.bindString(2, text);
        }
 
        String cateId = entity.getCateId();
        if (cateId != null) {
            stmt.bindString(3, cateId);
        }
 
        String createTime = entity.getCreateTime();
        if (createTime != null) {
            stmt.bindString(4, createTime);
        }
 
        Boolean isPublic = entity.getIsPublic();
        if (isPublic != null) {
            stmt.bindLong(5, isPublic ? 1l: 0l);
        }
        stmt.bindString(6, entity.getSiteId());
        stmt.bindLong(7, entity.getCategoryId());
        stmt.bindLong(8, entity.getUserId());
    }

    @Override
    protected void attachEntity(MTGrain entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    /** @inheritdoc */
    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.getLong(offset + 0);
    }    

    /** @inheritdoc */
    @Override
    public MTGrain readEntity(Cursor cursor, int offset) {
        MTGrain entity = new MTGrain( //
                cursor.getLong(offset + 0), // grainId
                cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // text
                cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // cateId
                cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // createTime
                cursor.isNull(offset + 4) ? null : cursor.getShort(offset + 4) != 0, // isPublic
                cursor.getString(offset + 5), // siteId
                cursor.getLong(offset + 6), // categoryId
                cursor.getLong(offset + 7) // userId
        );
        return entity;
    }
     
    /** @inheritdoc */
    @Override
    public void readEntity(Cursor cursor, MTGrain entity, int offset) {
        entity.setGrainId(cursor.getLong(offset + 0));
        entity.setText(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
        entity.setCateId(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
        entity.setCreateTime(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
        entity.setIsPublic(cursor.isNull(offset + 4) ? null : cursor.getShort(offset + 4) != 0);
        entity.setSiteId(cursor.getString(offset + 5));
        entity.setCategoryId(cursor.getLong(offset + 6));
        entity.setUserId(cursor.getLong(offset + 7));
     }
    
    /** @inheritdoc */
    @Override
    protected Long updateKeyAfterInsert(MTGrain entity, long rowId) {
        entity.setGrainId(rowId);
        return rowId;
    }
    
    /** @inheritdoc */
    @Override
    public Long getKey(MTGrain entity) {
        if (entity != null) {
            return entity.getGrainId();
        } else {
            return null;
        }
    }

    /** @inheritdoc */
    @Override    
    protected boolean isEntityUpdateable() {
        return true;
    }
    
    /** Internal query to resolve the "grains2User" to-many relationship of MTUser. */
    public List<MTGrain> _queryMTUser_Grains2User(long userId) {
        synchronized (this) {
            if (mTUser_Grains2UserQuery == null) {
                QueryBuilder<MTGrain> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.UserId.eq(null));
                mTUser_Grains2UserQuery = queryBuilder.build();
            }
        }
        Query<MTGrain> query = mTUser_Grains2UserQuery.forCurrentThread();
        query.setParameter(0, userId);
        return query.list();
    }

    /** Internal query to resolve the "grains2Site" to-many relationship of MTSite. */
    public List<MTGrain> _queryMTSite_Grains2Site(String siteId) {
        synchronized (this) {
            if (mTSite_Grains2SiteQuery == null) {
                QueryBuilder<MTGrain> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.SiteId.eq(null));
                mTSite_Grains2SiteQuery = queryBuilder.build();
            }
        }
        Query<MTGrain> query = mTSite_Grains2SiteQuery.forCurrentThread();
        query.setParameter(0, siteId);
        return query.list();
    }

    /** Internal query to resolve the "grains2Category" to-many relationship of MTCategory. */
    public List<MTGrain> _queryMTCategory_Grains2Category(long categoryId) {
        synchronized (this) {
            if (mTCategory_Grains2CategoryQuery == null) {
                QueryBuilder<MTGrain> queryBuilder = queryBuilder();
                queryBuilder.where(Properties.CategoryId.eq(null));
                mTCategory_Grains2CategoryQuery = queryBuilder.build();
            }
        }
        Query<MTGrain> query = mTCategory_Grains2CategoryQuery.forCurrentThread();
        query.setParameter(0, categoryId);
        return query.list();
    }

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getMTSiteDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T1", daoSession.getMTUserDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T2", daoSession.getMTCategoryDao().getAllColumns());
            builder.append(" FROM MTGRAIN T");
            builder.append(" LEFT JOIN MTSITE T0 ON T.'SITE_ID'=T0.'SITE_ID'");
            builder.append(" LEFT JOIN MTUSER T1 ON T.'USER_ID'=T1.'USER_ID'");
            builder.append(" LEFT JOIN MTCATEGORY T2 ON T.'CATEGORY_ID'=T2.'_id'");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }

    protected MTGrain loadCurrentDeep(Cursor cursor, boolean lock) {
        MTGrain entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        MTSite mTSite = loadCurrentOther(daoSession.getMTSiteDao(), cursor, offset);
        if (mTSite != null) {
            entity.setMTSite(mTSite);
        }
        offset += daoSession.getMTSiteDao().getAllColumns().length;

        MTUser mTUser = loadCurrentOther(daoSession.getMTUserDao(), cursor, offset);
        if (mTUser != null) {
            entity.setMTUser(mTUser);
        }
        offset += daoSession.getMTUserDao().getAllColumns().length;

        MTCategory mTCategory = loadCurrentOther(daoSession.getMTCategoryDao(), cursor, offset);
        if (mTCategory != null) {
            entity.setMTCategory(mTCategory);
        }

        return entity;
    }
    
    public MTGrain loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();

        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);

        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }

    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<MTGrain> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<MTGrain> list = new ArrayList<MTGrain>(count);

        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }
    
    protected List<MTGrain> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }
    
    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<MTGrain> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }
    
/**
     * Properties of entity MTGrain.<br/>
     * Can be used for QueryBuilder and for referencing column names.
    */
    public static class Properties {
        public final static Property GrainId = new Property(0, long.class, "grainId", true, "GRAIN_ID");
        public final static Property Text = new Property(1, String.class, "text", false, "TEXT");
        public final static Property CateId = new Property(2, String.class, "cateId", false, "CATE_ID");
        public final static Property CreateTime = new Property(3, String.class, "createTime", false, "CREATE_TIME");
        public final static Property IsPublic = new Property(4, Boolean.class, "isPublic", false, "IS_PUBLIC");
        public final static Property SiteId = new Property(5, String.class, "siteId", false, "SITE_ID");
        public final static Property CategoryId = new Property(6, long.class, "categoryId", false, "CATEGORY_ID");
        public final static Property UserId = new Property(7, long.class, "userId", false, "USER_ID");
    }
 
}
